# -*- encoding: utf-8 -*-
'''
@File    :   config.py   
@Contact :   desufnocs@163.com
@des     :   全局变量
 
@Modify Time       @Author      @Version    @Desciption
------------      ----------    --------    -----------
2025/2/17 19:04   AssenImpact      1.0         None
'''
import json
import os
import sys

from control.core.Utils import show_window_message

# 项目路径，以run.py所在目录为基础目录
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if getattr(sys, 'frozen', False):  # 检测是否被 PyInstaller 打包
    BASE_DIR = os.path.dirname(sys.executable)  # 获取 EXE 文件所在目录
else:
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def get_config(filename=os.path.join(BASE_DIR, "settings.txt")):
    """
    获取预设的配置文件，配置文件详细参数见settings.txt
    :param filename:
    :return:
    """
    default_config = {
        "port": 9527,
        "allow_hosts": ["*"],
        "create_qrcode": 1,
        "create_token_file": 1,
        "developer_mode": 0,
        "log_keep": 7
    }
    try:
        with open(filename, "r", encoding="utf-8") as f:
            config = {}
            for line in f.readlines():
                data = line.strip()
                if line[0] not in ["#", "\n"]:
                    if "PORT=" in data:
                        config["port"] = int(data.split("=")[1].strip())
                    elif "ALLOW_HOSTS=" in data:
                        config["allow_hosts"] = json.loads(data.split("=")[1].strip())
                    elif "CREATE_QRCODE=" in data:
                        config["create_qrcode"] = int(data.split("=")[1].strip())
                    elif "TOKEN_CIPHERTEXT=" in data:
                        config["token_ciphertext"] = data.split("=")[1].strip()
                    elif "CREATE_TOKEN_FILE=" in data:
                        config["create_token_file"] = int(data.split("=")[1].strip())
                    elif "DEVELOPER_MODE=" in data:
                        config["developer_mode"] = int(data.split("=")[1].strip())
                    elif "LOG_KEEP=" in data:
                        config["log_keep"] = int(data.split("=")[1].strip())
                    else:
                        pass
            return {**default_config, **config}
    except json.decoder.JSONDecodeError:
        show_window_message("配置文件数据错误，请按照settings.txt内注释修改配置")
        return default_config
    except FileNotFoundError:
        show_window_message("无配置文件，为了设备安全，请前往项目目录下settings.txt进行配置")
        return default_config


# 获取setttings.txt配置
CONFIG = get_config()
# 用于生成token的密文
TOKEN_CIPHERTEXT = CONFIG["token_ciphertext"]
# 端口号
PORT = CONFIG["port"]
# 允许来源
ALLOW_HOSTS = CONFIG["allow_hosts"]
# 是否生成二维码
CREATE_QRCODE = CONFIG["create_qrcode"]
# 是否生成密钥文件
CREATE_TOKEN_FILE = CONFIG["create_token_file"]
# 开发模式
DEVELOPER_MODE = CONFIG["developer_mode"]
# 日志保存时间
LOG_KEEP = CONFIG["log_keep"]
